import mongoose from "mongoose"
import util from "@mazp/util"

const projectSchema = new mongoose.Schema({
  name: {
    type: String,
    unique: true,
    trim: true,
    required: [true, 'Project must have a name!'],
    maxlength: [20, 'A project name must have less or equal then 20 characters'],
    minlength: [1, 'A project name must have more or equal then 1 characters'],
  },
  originName: {
    type: String,
    select: false,
  },
  url: {
    type: String,
    require: [true, 'Project must have a url!'],
    default: "#",
    maxlength: [100, 'A project url must have less or equal then 100 characters'],
    minlength: [1, 'A project url must have more or equal then 1 characters'],
  },
  category: {
    type: String,
    required: [true, 'Project must have a category!'],
    enum: {
      values: ["frontEnd", "backEnd", "node"],
      message: 'category is either: forntEnd, backEnd, node'
    },
    maxlength: [10, 'A project category must have less or equal then 20 characters'],
    minlength: [1, 'A project category must have more or equal then 1 characters'],
  },
  desc: {
    type: String,
    required: [true, 'Project must have a description!'],
    maxlength: [200, 'A project description must have less or equal then 100 characters'],
    minlength: [1, 'A project description must have more or equal then 1 characters'],
    default: "Design & Development"
  },
  img: {
    type: String,
    maxlength: [100, 'A project img url must have less or equal then 100 characters'],
    minlength: [0, 'A project img url must have more or equal then 0 characters'],
    default: "default.img"
  },
  isDelete: {
    type: Boolean,
    select: false,
    default: false
  },
  createdAt: {
    type: Date,
    default: Date.now()
  }
})

projectSchema.pre("save", function (next) {
  this.originName = this.name
  next();
});
projectSchema.post("save", function (doc, next) {
  // @ts-ignore 清除字段
  doc.isDelete = undefined
  doc.originName = undefined
  next();
});
projectSchema.pre(/^find/, function (next) {
  this.find({ isDelete: { $eq: false } })
  next();
});
projectSchema.pre("findOneAndUpdate", function (next) {
  // 非删除情况下的更新，需要更新 origin
  let updateContent: Record<string, any> = this.getUpdate() || {}
  if (!updateContent.isDelete) {
    // 添加更新值
    updateContent.name && this.set({ originName: updateContent.name })
  }
  // 删除情况
  else {
    this.set({ name: util.randomChars(15) })
  }
  next();
});

export default mongoose.model('Project', projectSchema)

